import _ from 'lodash'
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { DispatchResult } from '../../../tools'
import { RouteQuery, RouteName } from '../../../tools/routeUtil'
import { buildEditFields, buildEmptyForm } from '../../../common/data/index'

import Api from '../../../components/tools/api'
import Message from '../../../components/message/index'

// 编辑页面
export default (layoutName: any, context: any) => {
  const router = useRouter()
  const store = useStore()
  const emptyForm: Function | undefined = buildEmptyForm(layoutName)
  const createName = layoutName + '-create'
  const editName = layoutName + '-edit'
  const formData = ref(emptyForm ? emptyForm() : {})
  const fields = computed(() => buildEditFields(layoutName, { context, store, formData }))
  const setFormValue = (key: any, value: any) => (formData.value[key] = value)
  const backAction = () => router.back()
  const init = async () => {
    const routeName = RouteName(router)
    const idValue = _.toNumber(RouteQuery(router, 'id'))
    if (routeName === createName) {
      formData.value = emptyForm ? emptyForm() : undefined
    } else if (routeName === editName) {
      try {
        const params = { id: idValue }
        const result = await Api.send(`/${layoutName}/get`, params)
        DispatchResult(result, {
          onSuccess: (data: any) => {
            formData.value = emptyForm ? emptyForm(data) : undefined
          },
          onError: (_data: any, message: any) => {
            Message({ message, type: 'error' })
          }
        })
      } catch (error) {
        console.log(error)
      }
    }
  }

  const submitAction = async () => {
    try {
      const routeName = RouteName(router)
      if (routeName === createName || routeName === editName) {
        let url = `/${layoutName}/create`
        if (routeName === editName) {
          url = `/${layoutName}/update`
        }
        const result = await Api.send(url, formData.value)
        DispatchResult(result, {
          onSuccess: (_data: any, message: any) => {
            Message({ message, type: 'success' })
            router.back()
          },
          onError: (_data: any, message: any) => {
            Message({ message, type: 'error' })
          }
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  return {
    formData,
    fields,
    setFormValue,
    backAction,
    submitAction,
    init,
    routeName: RouteName(router)
  }
}
